<?php


namespace App\Repositories;


use App\Enums\AccountCheckEnum;
use App\Exceptions\BasicException;
use App\Models\MainDB\AccountLog;
use App\Models\MainDB\Gift;
use App\Models\MainDB\GiftBackpack;
use App\Models\MainDB\User;
use Illuminate\Support\Facades\DB;

class AccountCheckRepository
{
    //accountLog统计
    public function getAccountByTime($startTime, $endTime)
    {
        if (empty($startTime) || empty($endTime)) {
            $startTime = date('Y-m-d', time() - 86400);
            $endTime = $startTime . ' 23:59:59';
        }
        $startTime = strtotime($startTime);
        $endTime = strtotime($endTime);
        $hasRecord = app('model_account_check_log')->where('time_start', $startTime)->where('time_end', $endTime)->first();
        if (!empty($hasRecord)) {
            $originData = $hasRecord['origin_data'];
            $originData = empty($originData) ? [] : json_decode($originData, true);
            $account = $originData;
        } else {
            $account = AccountLog::query()
                ->where('change_time', '>=', $startTime)
                ->where('change_time', '<', $endTime)
                ->selectRaw('count(1) as num, sum(user_money) as user_money, change_type')
                ->groupBy('change_type')
                ->get()
                ->toArray();
            $account = $this->indexToAssoc($account, 'type');
            //用户充值以recharge表为准
            unset($account[1]);
            $userRechargeMoney = $this->dailyRecharge($startTime, $endTime);
            $account[1] = [
                'num'         => 1,
                'user_money'  => $userRechargeMoney,
                'change_type' => 1,
            ];
            $originData = json_encode($account, true);
            $data = [
                'time_start'      => $startTime,
                'time_end'        => $endTime,
                'origin_data'     => $originData,
                'create_mic_time' => get_microtime(),
            ];
            app('model_account_check_log')->insert($data);
        }

        $accountDetail = $this->handleAccount($account);
        var_dump($accountDetail);
        die;
        $userAccountResult = $accountDetail['result'];
        $result = [
            'account_info' => $userAccountResult,
        ];
    }

    /**
     * 平台留存
     * @param $time
     * @param $dot
     * @return bool
     */
    public function account_remain($start_time,$end_time,$dot)
    {
        $time = date('Y-m-d 00:00:',$end_time)."%";
        $remain = app('model_account_remind')->where('created_at','like',$time)->first();
        if ($remain){
            $data = [
                'origin_data'     => $remain->origin_data,
                'out_text'        => $remain->out_text,
                'start_time'      => $start_time,
                'end_time'        => $end_time-1,
                'ranges'          => $dot,
            ];
            app('model_account_remain_stat')->insert($data);
        }
    }

    /**
     * 游戏收益格式化脚本存储到统计表
     * @param $data
     * @param $start_time
     * @param $end_time
     * @param $ranges
     * @return bool
     */
    public function account_game_stat($start_time,$end_time,$ranges)
    {
        $exist = app('model_account_game_data')->where('start_time',$start_time)->where('ranges',$ranges)->first();
        if ($exist){
            return true;
        }
        //每日投入指标
        $dailyInc = $this->dailyIncome($start_time, $end_time);
        //
//        $dailyInc['lucky_truntable_add'] = $this->luckyInOutCome($start_time,$ranges,'income');
//        $dailyInc['lucky_truntable_common_add'] = $this->luckyCommonInOutCome($start_time,$ranges,'income');

        $dbData = [];
        //系统收入
        foreach ($dailyInc as $k => $v) {
            $dbData[] = [
                'change_type' => $v['type'],
                'money' => $v['money'],
                'origin_data' => empty($v['origin_data']) ? '' : json_encode($v['origin_data']),
                'change_flag' => 1,
                'start_time' => $start_time,
                'end_time' => $end_time,
            ];
        }
        //系统产出指标
        $dayDecr = $this->dailyDecr($start_time, $end_time);
        //幸运大转盘产出
//        $dayDecr['lucky_truntable_out'] = $this->luckyInOutCome($start_time,$ranges,'outcome');
//        幸运大转盘公池产出
//        $dayDecr['lucky_truntable_common_out'] = $this->luckyCommonInOutCome($start_time,$ranges,'outcome');

        foreach ($dayDecr as $k => $v) {
            $dbData[] = [
                'change_type' => $v['type'],
                'money' => 0 - $v['money'],
                'origin_data' => empty($v['origin_data']) ? '' : json_encode($v['origin_data']),
                'change_flag' => 2,
                'start_time' => $start_time,
                'end_time' => $end_time,
            ];
        }
        //盲盒产出与收益
        $boxMoney = $this->getBoxSendMoney($start_time,$end_time);
        $boxDbData = $boxMoney['dbData'];
        $dbData = array_merge($dbData, $boxDbData);
        //糖果产出与收益
        $candyMoney = $this->getCandyMoney($start_time,$end_time);
        $candyDbData = $candyMoney['dbData'];

        $dbData = array_merge($dbData, $candyDbData);
        //对游戏进行分组格式化处理
        $groups =[
            'tree'  =>[AccountCheckEnum::TREE_ADD,AccountCheckEnum::TREE_MONEY_DECR],       //鱼跃龙门
//            'hu'    =>[23,32],      //霍克
            'gift'  =>[19,28],      //盲盒
//            'candy' =>[21,30],      //抢麦 抢糖果 抢星钻
            'tree_common'=>[27,36], //鱼跃龙门公池
            'tree_self'=>[25,34],   //鱼跃龙门私池
            'turntable'=>[40,41], //幸运大转盘
//            'turntable_common'=>[45,44], //幸运大转盘
        ];
        $insert = [];
        foreach ($groups as $key=>$group){
            $temp = [];
            $temp['input'] = 0;
            $temp['output'] = 0;
            foreach ($dbData as $item){
                if ($item['change_type']==$group[0]){
                    $temp['input'] = (int)abs($item['money']);
                }
                if ($item['change_type'] == $group[1]){
                    $temp['output'] = (int)abs($item['money']);
                }
            }
            $gain = $temp['input'] - $temp['output'];
            $temp['gain'] =  $gain < 0 ? $gain : '+' . $gain;
            $insert[$key] = $temp;
        }

        app('model_account_game_data')->insert([
           'treasure_box_add'   => $insert['gift']['input'],
           'treasure_box_sum'   => $insert['gift']['output'],
           'treasure_box_gain'  => $insert['gift']['gain'],
           'fish_leap_add'      => $insert['tree']['input'],
           'fish_leap_sum'      => $insert['tree']['output'],
           'fish_leap_gain'     => $insert['tree']['gain'],
           'fish_leap_common_add'=> $insert['tree_common']['input'],
           'fish_leap_common_sum'=> $insert['tree_common']['output'],
           'fish_leap_common_gain'=> $insert['tree_common']['gain'],
           'lucky_spin_add'     => $insert['turntable']['input'],
           'lucky_spin_sum'     => $insert['turntable']['output'],
           'lucky_spin_gain'    => $insert['turntable']['gain'],
           'lucky_spin_common_add'=> 0,
           'lucky_spin_common_sum'=> 0,
           'lucky_spin_common_gain'=> 0,
            'start_time'        =>  $start_time,
            'end_time'          =>  $end_time,
            'ranges'            =>  $ranges,
            'created_at'        =>  time(),
        ]);
    }

    //定时任务统计留存及各类型资金明细
    public function crontabAccount($startTime, $endTime, $isDaily = false)
    {
        $micTime = get_microtime();
        if (!$isDaily) {
            //现有留存
            $levelAll = $this->accountRemind($micTime);
            $str = "留存截止至:" . date('Y-m-d H:i:s') . PHP_EOL;
            foreach ($levelAll as $k => $v) {
                $str .= $v['name'] . $v['money'] . PHP_EOL;
            }
            $data = [
                'origin_data' => json_encode($levelAll),
                'out_text' => $str,
                'create_mic_time' => $micTime,
            ];
            app('model_account_remind')->insert($data);
        }

        //每日投入指标
        $dailyInc = $this->dailyIncome($startTime, $endTime);
        $dbData = [];
        //系统收入
        foreach ($dailyInc as $k => $v) {
            $dbData[] = [
                'change_type' => $v['type'],
                'money' => $v['money'],
                'origin_data' => empty($v['origin_data']) ? '' : json_encode($v['origin_data']),
                'change_flag' => 1,
                'start_time' => $startTime,
                'end_time' => $endTime,
            ];
        }
        //系统产出指标
        $dayDecr = $this->dailyDecr($startTime, $endTime);
        foreach ($dayDecr as $k => $v) {
            $dbData[] = [
                'change_type' => $v['type'],
                'money' => 0 - $v['money'],
                'origin_data' => empty($v['origin_data']) ? '' : json_encode($v['origin_data']),
                'change_flag' => 2,
                'start_time' => $startTime,
                'end_time' => $endTime,
            ];
        }
        //盲盒产出与收益
        $boxMoney = $this->getBoxSendMoney($startTime, $endTime);
        $boxDbData = $boxMoney['dbData'];
        $dbData = array_merge($dbData, $boxDbData);
        //糖果产出与收益
        $candyMoney = $this->getCandyMoney($startTime, $endTime);

        $candyDbData = $candyMoney['dbData'];

        $dbData = array_merge($dbData, $candyDbData);
        // //霍克游戏投入产出
        // $hukeMoney = $this->shakeHuoKe(strtotime($startTime), strtotime($endTime));
        // $hukeMoneyAdd = $hukeMoney['allinput'];
        // $hukeMoneyDecr = $hukeMoney['alloutput'];
        // $dbData[] = [
        //     'change_type' => AccountCheckEnum::HU_KE_GAME_ADD,
        //     'money'       => $hukeMoneyAdd,
        //     'origin_data' => json_encode($hukeMoneyAdd),
        //     'change_flag' => 1,
        //     'start_time'  => strtotime($startTime),
        //     'end_time'    => strtotime($endTime),
        // ];
        // $dbData[] = [
        //     'change_type' => AccountCheckEnum::HU_KE_GAME_OUT,
        //     'money'       => 0 - $hukeMoneyDecr,
        //     'origin_data' => json_encode($hukeMoneyDecr),
        //     'change_flag' => 2,
        //     'start_time'  => strtotime($startTime),
        //     'end_time'    => strtotime($endTime),
        // ];
        /*$hukeMoneyAdd = $this->addGameData(strtotime($startTime), strtotime($endTime));
        $dbData[] = [
            'change_type' => AccountCheckEnum::HU_KE_GAME_ADD,
            'money'       => $hukeMoneyAdd,
            'origin_data' => json_encode($hukeMoneyAdd),
            'change_flag' => 1,
            'start_time'  => strtotime($startTime),
            'end_time'    => strtotime($endTime),
        ];
        //霍克游戏产出
        $hukeMoneyDecr = $this->sumGameData(strtotime($startTime), strtotime($endTime));
        $dbData[] = [
            'change_type' => AccountCheckEnum::HU_KE_GAME_OUT,
            'money'       => 0 - $hukeMoneyDecr,
            'origin_data' => json_encode($hukeMoneyDecr),
            'change_flag' => 2,
            'start_time'  => strtotime($startTime),
            'end_time'    => strtotime($endTime),
        ];*/
        if (!$isDaily) {
            app('model_account_check_daily_stat')->insert($dbData);
        } else {
            app('model_account_check_daily_stat_real')->insert($dbData);
        }
    }

    //糖果投入及产出
    public function getCandyMoney($startTime, $endTime)
    {
        $res = app('model_game_sugar_record')->select(DB::raw('sum(get_num) as sum_get_money'), DB::raw('sum(cost) as sum_cost'))->where('create_time', '>=', $startTime)->where('create_time', '<', $endTime)->first();
        $res = empty($res) ? [] : $res->toArray();
        $returnData = [
            'list'   => $res,
            'dbData' => [
                [
                    'change_type' => AccountCheckEnum::CANDY_MONEY_BUY,
                    'money'       => $res['sum_cost'] ?? 0,
                    'origin_data' => json_encode($res),
                    'change_flag' => 1,
                    'start_time'  => $startTime,
                    'end_time'    => $endTime,
                ],
                [
                    'change_type' => AccountCheckEnum::CANDY_MONEY_OUT,
                    'money'       => 0 - ($res['sum_get_money'] ?? 0),
                    'origin_data' => json_encode($res),
                    'change_flag' => 2,
                    'start_time'  => $startTime,
                    'end_time'    => $endTime,
                ],
            ],
        ];

        return $returnData;
    }

    //资金留存指标

    /**
     * @param  string  $micTime
     * @return array[]
     */
    public function accountRemind($micTime = '')
    {
        //用户存量金币
        $levelMoney = $this->getUserMoneyLevel();
        //用户存量收益
        $levelEarning = $this->getUserEarnings();
        //用户背包价值
        $levelBackpackPrice = $this->getUserBackPackSumPrice();
        //公会整体收益 +余额
        $levelSocial = $this->sociatyEarningsKeep();
        $levelSocialPrice = $levelSocial['sumMoney'];
        $levelSocialEarning = $levelSocial['sumEarnings'];
        //用户总体水滴价值
        $water = $this->getUserLevelWaterPrice();;
        $waterSumMoney = $water['sum_money'];
        //霍克游戏钻石数量
        // $huKeCoinData = $this->allBalanceAndReward();
        // $huKeCoin = empty($huKeCoinData['blancne']['coin']) ? 0 : $huKeCoinData['blancne']['coin'];
        //提现中的金额数
        $waitWithDrawMoney = $this->getWaitWithdrawMoney();

        $data = [
            [
                'type'            => AccountCheckEnum::MONEY,
                'money'           => $levelMoney,
                'name'            => '平台所有用户总余额:',
                'origin_data'     => $levelMoney,
                'create_mic_time' => $micTime,
            ],
            [
                'type'            => AccountCheckEnum::EARNING,
                'money'           => $levelEarning,
                'name'            => '平台所有用户总收益:',
                'origin_data'     => $levelEarning,
                'create_mic_time' => $micTime,
            ],
            [
                'type'            => AccountCheckEnum::BACK_PACK,
                'money'           => $levelBackpackPrice,
                'name'            => '平台所有用户背包礼物价值:',
                'origin_data'     => $levelBackpackPrice,
                'create_mic_time' => $micTime,
            ],
            [
                'type'            => AccountCheckEnum::SOCIAL_EARNING,
                'money'           => $levelSocialEarning,
                'name'            => '公会收益:',
                'origin_data'     => $levelSocialEarning,
                'create_mic_time' => $micTime,
            ],
            [
                'type'            => AccountCheckEnum::SOCIAL_MONEY,
                'money'           => $levelSocialPrice,
                'name'            => '公会余额:',
                'origin_data'     => $levelSocialPrice,
                'create_mic_time' => $micTime,
            ],
            [
                'type'            => AccountCheckEnum::WATER,
                'money'           => $waterSumMoney,
                'name'            => '总水滴价值:',
                'origin_data'     => json_encode($water),
                'create_mic_time' => $micTime,
            ],
            // [
            //     'type'            => AccountCheckEnum::HU_KE,
            //     'money'           => $huKeCoin,
            //     'name'            => '霍克游戏钻石价值金币数:',
            //     'origin_data'     => json_encode($huKeCoinData),
            //     'create_mic_time' => $micTime,
            // ],
            [
                'type'            => AccountCheckEnum::WITH_DRAW,
                'money'           => $waitWithDrawMoney,
                'name'            => '提现审核中金币数:',
                'origin_data'     => json_encode($waitWithDrawMoney),
                'create_mic_time' => $micTime,
            ],
        ];

        return $data;
    }

    //每日指标 -- 减量
    public function dailyDecr($startTime, $endTime)
    {
        if (empty($startTime) || empty($endTime)) {
            $startTime = date('Y-m-d', time() - 86400);
            $endTime = $startTime . " 23:59:59";
        }
        $starStartTime = date('Y-m-d H:i:s',$startTime);
        $starEndTime = date('Y-m-d H:i:s',$endTime);

        //公会收益减少
        $sociatyDecrMoney = $this->sociatyEarningsDec($startTime, $endTime);
        //许愿树产出
        $treeDecrMoney = $this->waterDropDec($startTime, $endTime);
        //许愿树产出公池
        $treeDecrMoneyCommon = $this->waterDropDecCommon($startTime, $endTime);
        //许愿树产出私池
        $treeDecrMoneySelf = $this->waterDropDecSelf($startTime, $endTime);

        // 星之许愿池产出
        $starDecrMoneySelf = $this->starDropDecSelf($starStartTime, $starEndTime);

        //守护单独表
        $fmProtectMoneyOrigin = $this->fmProtectDec($startTime, $endTime);
        //购买战令
        $warOrderDecOrigin = $this->warOrderDec($startTime, $endTime);
        //购买爵位

        //涉及的消耗的资金变更 取 accountLog
        $rechargeDecr = $this->dailyAccountChange($startTime, $endTime);
        $giftDecrMoney = $withDraMoney = $buyMallMoney = $headLineMoney = $adminDecrMoney = $adminDecrEarning = $buyNobiRecordMoney = $buyZhanlingRecordMoney = $openGuardRecordMoney = 0;
        foreach ($rechargeDecr as $k => $v) {
            if ($v['change_type'] == 2) {    //提现成功
                $withDraMoney += $v['user_money'];
            } else {
                if ($v['change_type'] == 19 || $v['change_type'] == 220 || $v['change_type'] == 221) {   //购买个性商品
                    $buyMallMoney += $v['user_money'];
                } else {
                    if ($v['change_type'] == 134) { //上头条
                        $headLineMoney += $v['user_money'];
                    } else {
                        if ($v['change_type'] == 22) { //后台余额减少
                            $adminDecrMoney += $v['user_money'];
                        } else {
                            if ($v['change_type'] == 17) { //后台收益减少
                                $adminDecrEarning += $v['user_money'];
                            } else {
                                if ($v['change_type'] == 5) { //购买爵位资金减少
                                    $buyNobiRecordMoney += $v['user_money'];
                                } else {
                                    if ($v['change_type'] == 57 || $v['change_type'] == 56) { //购买战令相关
                                        $buyZhanlingRecordMoney += $v['user_money'];
                                    } else {
                                        if ($v['change_type'] == 25) { //开通守护
                                            $openGuardRecordMoney += $v['user_money'];
                                        } else {
                                            if ($v['change_type'] == 4 || $v['change_type'] == 9) {   //送礼的支出（包括盲盒）
                                                $giftDecrMoney += $v['user_money'];
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return [
            'withDraMoney'           => [
                'money'       => $withDraMoney,
                'type'        => AccountCheckEnum::WITHDRAW,
                'origin_data' => $withDraMoney,
            ],
            'buyMallMoney'           => [
                'money'       => $buyMallMoney,
                'type'        => AccountCheckEnum::BUG_MALL,
                'origin_data' => $buyMallMoney,
            ],
            'headLineMoney'          => [
                'money'       => $headLineMoney,
                'type'        => AccountCheckEnum::HEADLINE,
                'origin_data' => $headLineMoney,
            ],
            'adminDecrMoney'         => [
                'money'       => $adminDecrMoney,
                'type'        => AccountCheckEnum::ADMIN_DECR_MONEY,
                'origin_data' => $adminDecrMoney,
            ],
            'adminDecrEarning'       => [
                'money'       => $adminDecrEarning,
                'type'        => AccountCheckEnum::ADMIN_DECR_EARNING,
                'origin_data' => $adminDecrEarning,
            ],
            'buyNobiRecordMoney'     => [
                'money'       => $buyNobiRecordMoney,
                'type'        => AccountCheckEnum::NOBI_BUY,
                'origin_data' => $buyNobiRecordMoney,
            ],
            'buyZhanlingRecordMoney' => [
                'money'       => $buyZhanlingRecordMoney,
                'type'        => AccountCheckEnum::ZHANLING_BUY,
                'origin_data' => $buyZhanlingRecordMoney,
            ],
            'openGuardRecordMoney'   => [
                'money'       => $openGuardRecordMoney,
                'type'        => AccountCheckEnum::GUARD_BUY,
                'origin_data' => $openGuardRecordMoney,
            ],
            'giftDecrMoney'          => [
                'money'       => $giftDecrMoney,
                'type'        => AccountCheckEnum::GIFT_DECR,
                'origin_data' => $giftDecrMoney,
            ],
            'sociatyDecrMoney'       => [
                'money'       => $sociatyDecrMoney,
                'type'        => AccountCheckEnum::SOCIAL_MONEY_DECR,
                'origin_data' => $sociatyDecrMoney,
            ],
            'treeDecrMoney'          => [
                'money'       => $treeDecrMoney,
                'type'        => AccountCheckEnum::TREE_MONEY_DECR,
                'origin_data' => $treeDecrMoney,
            ],
            'fmProtectMoneyOrigin'   => [
                'money'       => $fmProtectMoneyOrigin,
                'type'        => AccountCheckEnum::FM_MONEY_ORIGIN,
                'origin_data' => $fmProtectMoneyOrigin,
            ],
            'warOrderDecOrigin'      => [
                'money'       => $warOrderDecOrigin,
                'type'        => AccountCheckEnum::WAR_ORDER_ORIGIN,
                'origin_data' => $warOrderDecOrigin,
            ],
            'treeDecrMoneySelf'          => [
                'money'       => $treeDecrMoneySelf,
                'type'        => AccountCheckEnum::TREE_MONEY_DECR_SELF,
                'origin_data' => $treeDecrMoneySelf,
            ],
            'treeDecrMoneyCommon'          => [
                'money'       => $treeDecrMoneyCommon,
                'type'        => AccountCheckEnum::TREE_MONEY_DECR_COMMON,
                'origin_data' => $treeDecrMoneyCommon,
            ],
            'starDecrMoneyCommon'          => [
                'money'       => $starDecrMoneySelf,
                'type'        => AccountCheckEnum::STAR_MONEY_DECR_COMMON,
                'origin_data' => $starDecrMoneySelf,
            ],
        ];
    }


    //送礼减少的值
    public function dailyGiftChange($startTime, $endTime)
    {
        $money = app('model_give_gift')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->sum('total_price');
        $money = empty($money) ? [] : $money->toArray();

        return $money;
    }

    //减少的accountLog表的变更记录
    public function dailyAccountChange($startTime, $endTime)
    {
        $startTime = date('Y-m-d H:i:s',$startTime);
        $endTime = date('Y-m-d H:i:s',$endTime);
        // $typeMoney = app('model_account_log')->where('change_time', '>=', $startTime)->where('change_time', '<', $endTime)->groupBy('change_type')->select('change_type', DB::raw('sum(user_money) as user_money'))->get();
        $typeMoney = app('model_account_money_log')->where('created_at', '>=', $startTime)->where('created_at', '<', $endTime)->groupBy('change_type')->select('change_type', DB::raw('sum(change_money) as user_money'))->get();

        $typeMoney = empty($typeMoney) ? [] : $typeMoney->toArray();

        return $typeMoney;
    }

    //每日指标 -- 全部每日增量
    public function dailyIncome($startTime, $endTime)
    {
        if (empty($startTime) || empty($endTime)) {
            $startTime = time() - 86400;
            $endTime = strtotime(date('Y-m-d'));
        }
        $starStartTime = date('Y-m-d H:i:s',$startTime);
        $starEndTime = date('Y-m-d H:i:s',$endTime);
        //每日增量充值金币数
        $dailyRechargeMoney = $this->dailyRecharge($startTime, $endTime);
        //后台充值金额或收益
        $dailyAdminRecharge = $this->dailyAdminRechargeGet($startTime, $endTime);
        $dailyAdminRechargeMoney = isset($dailyAdminRecharge[1]) ? $dailyAdminRecharge[1]['sum_gold'] : 0;    //后台充值金额
        $dailyAdminRechargeEarning = isset($dailyAdminRecharge[2]) ? $dailyAdminRecharge[2]['sum_gold'] : 0;  //后台充值收益
        $dailyAdminRechargeSpecial = isset($dailyAdminRecharge[3]) ? $dailyAdminRecharge[3]['sum_gold'] : 0;  //后台充值特殊币

        //许愿树奖池投入
        $dailyTreeAddMoney = $this->dailyTreeIncrMoney($startTime, $endTime);
        //许愿树奖池投入私池
        $dailyTreeAddSelfMoney = $this->dailyTreeSelfIncrMoney($startTime, $endTime);
        //许愿树奖池投入公池
        $dailyTreeAddCommonMoney = $this->dailyTreeCommonIncrMoney($startTime, $endTime);

        // 礼物的收益
        $giftGetMoney = $this->giftIncrMoney($startTime, $endTime);

        //霍克城堡总体反补
        //        $huKeMoney = $this->addGameData($startTime, $endTime);
        //公会收益
        $socialMoney = $this->sociatyEarningsInc($startTime, $endTime);
        //购买爵位返利
        $dailyNobilityMoney = $this->dailyBuyNobility($startTime, $endTime);

        // 星之许愿池投入
        $starWishingMoney = $this->dailyBuyStar($starStartTime, $starEndTime);

        return [
            'dailyRechargeMoney'        => [
                'money'       => $dailyRechargeMoney,
                'type'        => AccountCheckEnum::RECHARGE,
                'origin_data' => $dailyRechargeMoney,
            ],
            'dailyAdminRechargeMoney'   => [
                'money'       => $dailyAdminRechargeMoney,
                'type'        => AccountCheckEnum::ADMIN_RECHARGE,
                'origin_data' => $dailyAdminRechargeMoney,
            ],
            'dailyAdminRechargeEarning' => [
                'money'       => $dailyAdminRechargeEarning,
                'type'        => AccountCheckEnum::ADMIN_EARNING,
                'origin_data' => $dailyAdminRechargeEarning,
            ],
            'dailyAdminRechargeSpecial' => [
                'money'       => $dailyAdminRechargeSpecial,
                'type'        => AccountCheckEnum::ADMIN_SPECIAL,
                'origin_data' => $dailyAdminRechargeSpecial,
            ],
            'dailyTreeAddMoney'         => [
                'money'       => $dailyTreeAddMoney,
                'type'        => AccountCheckEnum::TREE_ADD,
                'origin_data' => $dailyTreeAddMoney,
            ],
            'giftIncrMoney'             => [
                'money'       => $giftGetMoney,
                'type'        => AccountCheckEnum::GIFT_EARNING_ADD,
                'origin_data' => $giftGetMoney,
            ],
            //            'huKeMoney'                 => [
            //                'money'       => $huKeMoney,
            //                'type'        => AccountCheckEnum::HU_KE_ADD,
            //                'origin_data' => $huKeMoney,
            //            ],
            'dailyNobilityMoney'        => [
                'money'       => $dailyNobilityMoney,
                'type'        => AccountCheckEnum::NOBI_RETURN,
                'origin_data' => $dailyNobilityMoney,
            ],
            'socialMoney'               => [
                'money'       => $socialMoney,
                'type'        => AccountCheckEnum::SOCIAL_MONEY_ADD,
                'origin_data' => $socialMoney,
            ],
            'dailyTreeAddSelfMoney'               => [
                'money'       => $dailyTreeAddSelfMoney,
                'type'        => AccountCheckEnum::TREE_ADD_SELF,
                'origin_data' => $dailyTreeAddSelfMoney,
            ],
            'dailyTreeAddCommonMoney'               => [
                'money'       => $dailyTreeAddCommonMoney,
                'type'        => AccountCheckEnum::TREE_ADD_COMMON,
                'origin_data' => $dailyTreeAddCommonMoney,
            ],
            'dailyStarAddCommonMoney'               => [
                'money'       => $starWishingMoney,
                'type'        => AccountCheckEnum::STAR_ADD_COMMON,
                'origin_data' => $starWishingMoney,
            ],
        ];
    }

    //盲盒赠送/收益金钱
    public function getBoxSendMoney($startTime, $endTime)
    {
        $res = app('model_gift_box_prize_detail')->select(DB::raw('sum(gold_coin) as total_out_gold, type,sum(number) as total_buy_number'))->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->groupBy('type')->get();
        $res = empty($res) ? [] : $res->toArray();
        if (empty($res)) {
            $returnData = [
                'boxBuyMoney' => [
                    'money'       => 0,
                    'type'        => AccountCheckEnum::GIFT_BOX_MONEY_BUY,
                    'origin_data' => '',
                ],
                'boxOutMoney' => [
                    'money'       => 0,
                    'type'        => AccountCheckEnum::GIFT_BOX_MONEY_OUT,
                    'origin_data' => '',
                ],
                'list'        => [],
            ];
            //投入
            $dbData[] = [
                'change_type' => $returnData['boxBuyMoney']['type'],
                'money'       => $returnData['boxBuyMoney']['money'],
                'origin_data' => empty($returnData['boxBuyMoney']['origin_data']) ? '' : json_encode($returnData['boxBuyMoney']['origin_data']),
                'change_flag' => 1,
                'start_time'  => $startTime,
                'end_time'    => $endTime,
            ];
            //产出
            $dbData[] = [
                'change_type' => $returnData['boxOutMoney']['type'],
                'money'       => 0 - $returnData['boxOutMoney']['money'],
                'origin_data' => empty($returnData['boxOutMoney']['origin_data']) ? '' : json_encode($returnData['boxOutMoney']['origin_data']),
                'change_flag' => 2,
                'start_time'  => $startTime,
                'end_time'    => $endTime,
            ];
            $returnData['dbData'] = $dbData;

            return $returnData;
        }
        $giftIds = [295, 296, 320];
        $giftList = app('model_gift')->whereIn('id', $giftIds)->get(['id', 'price']);
        $giftList = empty($giftList) ? [] : $giftList->toArray();
        $giftList = $this->indexToAssoc($giftList, 'id');
        foreach ($res as $k => $v) {
            //1银 2金 3铜
            if ($v['type'] == 1) {
                $typeToId = 295;
                $p = 2100;
                $desc = '银盲盒';
            } else {
                if ($v['type'] == 2) {
                    $typeToId = 296;
                    $p = 6600;
                    $desc = '金盲盒';
                } else {
                    $typeToId = 320;
                    $p = 600;
                    $desc = '铜盲盒';
                }
            }
            $price = !isset($giftList[$typeToId]) ? $giftList[$typeToId]['price'] : $p;
            $res[$k]['total_buy_money'] = $v['total_buy_number'] * $price;
            $res[$k]['price_id'] = $typeToId;
            $res[$k]['desc'] = $desc;
        }
        $boxMoneyOut = $boxMoneyBuy = 0;  //盲盒购买价值 盲盒产出价值
        foreach ($res as $k => $v) {
            $boxMoneyBuy += $v['total_buy_money'];
            $boxMoneyOut += $v['total_out_gold'];
        }
        $returnData = [
            'boxBuyMoney' => [
                'money'       => $boxMoneyBuy,
                'type'        => AccountCheckEnum::GIFT_BOX_MONEY_BUY,
                'origin_data' => $res,
            ],
            'boxOutMoney' => [
                'money'       => $boxMoneyOut,
                'type'        => AccountCheckEnum::GIFT_BOX_MONEY_OUT,
                'origin_data' => $res,
            ],
            'list'        => $res,
        ];
        //投入
        $dbData[] = [
            'change_type' => $returnData['boxBuyMoney']['type'],
            'money'       => $returnData['boxBuyMoney']['money'],
            'origin_data' => empty($returnData['boxBuyMoney']['origin_data']) ? '' : json_encode($returnData['boxBuyMoney']['origin_data']),
            'change_flag' => 1,
            'start_time'  => $startTime,
            'end_time'    => $endTime,
        ];
        //产出
        $dbData[] = [
            'change_type' => $returnData['boxOutMoney']['type'],
            'money'       => 0 - $returnData['boxOutMoney']['money'],
            'origin_data' => empty($returnData['boxOutMoney']['origin_data']) ? '' : json_encode($returnData['boxOutMoney']['origin_data']),
            'change_flag' => 2,
            'start_time'  => $startTime,
            'end_time'    => $endTime,
        ];
        $returnData['dbData'] = $dbData;

        return $returnData;
    }

    //幸运的大转盘用户投入产出
    public function luckyInOutCome($start_time,$range,$type)
    {
        //幸运大转盘
        $num = 0;
        $acctype = 0;
        $lucky_turntable = DB::connection('mysql_star')
            ->table('ln_star_wishing_well_lottery_stat_user')
            ->where('time_desc',date('Y-m-d',$start_time))
            ->where('time_type',$range+1)       //游戏的range从2开始的
            ->first();
        if ($lucky_turntable){
            if ($type=='income'){
                $num = $lucky_turntable->user_input_number;
                $acctype = AccountCheckEnum::LUCKEY_TURNTABLE_INCR;
            }
            if ($type=='outcome'){
                $num = $lucky_turntable->user_outnput_number;
                $acctype = AccountCheckEnum::LUCKEY_TURNTABLE_DECR;
            }
        }
        return [
            'money'       => $num,
            'type'        => $acctype,
            'origin_data' => $num,
        ];
    }

    //幸运的大转盘公池投入产出
    public function luckyCommonInOutCome($start_time,$range,$type)
    {
        //幸运大转盘公池
        $num = 0;
        $acctype = 0;
        $lucky_common = DB::connection('mysql_star')
            ->table('ln_star_wishing_well_lottery_stat_common')
            ->where('time_desc',date('Y-m-d',$start_time))
            ->where('time_type',$range+1)       //游戏的range从2开始的
            ->first();
        if ($lucky_common){
            if ($type=='income'){
                $num = $lucky_common->user_input_number;
                $acctype = AccountCheckEnum::LUCKEY_TURNTABLE_COMMON_INCR;
            }
            if ($type=='outcome'){
                $num = $lucky_common->user_outnput_number;
                $acctype = AccountCheckEnum::LUCKEY_TURNTABLE_COMMON_DECR;
            }

        }
        return [
            'money'       => $num,
            'type'        => $acctype,
            'origin_data' => $num,
        ];
    }


    //送礼收益增加量
    public function giftIncrMoney($startTime, $endTime)
    {
        $startTime = date('Y-m-d H:i:s',$startTime);
        $endTime = date('Y-m-d H:i:s',$endTime);
        // return app('model_account_log')->where('change_time', '>=', $startTime)->where('change_time', '<', $endTime)->where('change_type', 6)->sum('user_money');
        return app('model_account_earnings_log')->where('created_at', '>=', $startTime)->where('created_at', '<', $endTime)->where('change_type', 6)->sum('change_money');
    }

    //许愿树投入 -- 公池
    public function dailyTreeCommonIncrMoney($startTime, $endTime)
    {
        $sumMoney = app('model_gold_price')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->whereNotIn('pool_type', [40, 50])->sum('total_cost');

        return $sumMoney;
    }

    //许愿树投入 -- 私池
    public function dailyTreeSelfIncrMoney($startTime, $endTime)
    {
        $sumMoney = app('model_gold_price')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->whereIn('pool_type', [40, 50])->sum('total_cost');

        return $sumMoney;
    }

    //许愿树投入
    public function dailyTreeIncrMoney($startTime, $endTime)
    {
        $sumMoney = app('model_gold_price')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->sum('total_cost');

        return $sumMoney;
    }

    //每日指标 -- 每日充值金币总值
    public function dailyRecharge($startTime, $endTime, $userId = '')
    {
        $sumGold = app('model_user_recharge')->where('pay_time', '>=', $startTime)->where('pay_time', '<', $endTime)->where('status', 2);
        if (!empty($userId)) {
            $sumGold = $sumGold->where('user_id', $userId);
        }
        $sumGold = $sumGold->sum('gold');

        return $sumGold;
    }

    //每日指标 -- 每日后台充值余额或收益总值(recharge表)
    public function dailyAdminRechargeGet($startTime, $endTime)
    {
        $sumGold = app('model_admin_recharge')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->groupBy('type')->whereIn('type', [1, 2, 3])->select('type', DB::raw('sum(gold) as sum_gold'))->where('gold', '>', 0)->get();
        $sumGold = empty($sumGold) ? [] : $sumGold->toArray();
        $sumGold = $this->indexToAssoc($sumGold, 'type');

        return $sumGold;
    }

    //每日指标 -- 每日后台充值余额或收益总值(account_log表)
    /*public function dailyAdminRechargeGetByAccount($startTime,$endTime){
        $sumGold = app('model_user_recharge')->where('pay_time','>=',$startTime)->where('pay_time','<=',$endTime)->groupBy('type')->whereIn('type',[1,2,3])->select('type', DB::raw('sum(gold) as sum_gold'))->where('gold','>',0)->get();
        $sumGold = empty($sumGold)?[]:$sumGold->toArray();
        $sumGold = $this->indexToAssoc($sumGold,'type');
        return $sumGold;
    }*/

    //每日指标 -- 用户爵位返利
    public function dailyBuyNobility($startTime, $endTime)
    {
        $sumMoney = app('model_user_recharge')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->where('type', 7)->sum('money');

        return $sumMoney;
    }

    //每日指标 -- 星之许愿池
    public function dailyBuyStar($startTime, $endTime)
    {
        $sumMoney = app('model_game_star_lottery')->where('create_time', '>=', $startTime)->where('create_time', '<', $endTime)->sum('used_amount');

        return $sumMoney;
    }

    //每日指标 -- 购买爵位+爵位续费
    public function dailyBuyNobilityInc($startTime, $endTime)
    {
        $sumMoney = app('model_user_recharge')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->whereIn('type', [5, 20])->sum('money');

        return $sumMoney;
    }

    //每日指标 -- 购买进阶战令+购买战令等级
    public function warOrderDec($startTime, $endTime)
    {
        /*购买进阶战令*/
        $sumMoney1 = app('model_war_order_user_advanced')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->sum('cost_gold');
        /*购买战令等级*/
        $sumMoney2 = app('model_war_order_user_level')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->whereIn('type', [2])->sum('cost_gold');

        return $sumMoney1 + $sumMoney2;
    }

    //每日指标 -- 开通守护
    public function fmProtectDec($startTime, $endTime)
    {
        $sumMoney = app('model_fm_protect_list')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->sum('gold');

        return $sumMoney;
    }

    //许愿树产出 --公池
    public function waterDropDecCommon($startTime, $endTime)
    {
        $sumMoney = app('model_gold_price')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->whereNotIn('pool_type', [40, 50])->sum('number');

        return $sumMoney;
    }

    //许愿树产出 --  私池
    public function waterDropDecSelf($startTime, $endTime)
    {
        $sumMoney = app('model_gold_price')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->whereIn('pool_type', [40, 50])->sum('number');

        return $sumMoney;
    }

    //每日指标 -- 许愿树奖池总体产出
    public function waterDropDec($startTime, $endTime)
    {
        $sumMoney = app('model_gold_price')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->sum('number');

        return $sumMoney;

        $sumMoney = app('model_account_log')->where('change_time', '>=', $startTime)->where('change_time', '<', $endTime)->where('change_type', 133)->sum('user_money');

        return $sumMoney;
    }

    //星之许愿池产出
    public function starDropDecSelf($startTime, $endTime)
    {
        $sumMoney = app('model_game_star_lottery')->where('create_time', '>=', $startTime)->where('create_time', '<', $endTime)->sum('gift_all_price');

        return $sumMoney;
    }


    //用户金币余额
    public function getUserMoneyLevel()
    {
        $sumMoney = app('model_user')->sum('money');

        return $sumMoney;
    }

    //用户存量 收益（存余额）
    public function getUserEarnings()
    {
        $sumMoney = app('model_user')->sum('earnings');

        return $sumMoney;
    }

    //用户总体背包礼物价值
    public function getUserBackPackSumPrice()
    {
        $allPrice = app('model_gift_backpack')->select(DB::raw('sum(number*price) as sum_price'))->leftJoin('ln_gift as g', 'g.id', '=', 'ln_gift_backpack.gift_id')->first();

        return empty($allPrice['sum_price']) ? 0 : $allPrice['sum_price'];

        //        $groupPrice = app('model_gift_backpack')->select('gift_id', DB::raw('sum(number) as sum_number'))->groupBy('gift_id')->get();
        $groupPrice = empty($groupPrice) ? [] : $groupPrice->toArray();
        if (empty($groupPrice)) {
            return 0;
        }
        //        var_dump($groupPrice);die;
        $giftIds = $this->getArrayColumn($groupPrice, 'gift_id');
        $giftList = app('model_gift')->whereIn('id', $giftIds)->get(['price', 'id']);
        $giftList = empty($giftList) ? [] : $giftList->toArray();
        $giftList = $this->indexToAssoc($giftList, 'id');
        $sumMoney = 0;
        foreach ($groupPrice as $k => $v) {
            $price = isset($giftList[$v['gift_id']]) ? $giftList[$v['gift_id']]['price'] : 0;
            $sumMoney += $v['sum_number'] * $price;
        }

        return $sumMoney;
    }

    //用户当前总体水滴价值
    public function getUserLevelWaterPrice()
    {
        $waterSum = app('model_user')->sum('waterdrop_number');
        $numToMoney = app('model_config')->getValue('WATERDROP_PRICE');
        $numToMoney = empty($numToMoney) ? 200 : $numToMoney;

        return [
            'sum'       => $waterSum,
            'percent'   => $numToMoney,
            'sum_money' => $waterSum * $numToMoney,
        ];
    }

    //提现中的金额
    public function getWaitWithdrawMoney()
    {
        return app("model_user_withdraw")->where([
            ["status", "=", 1],
        ])->sum("gold");
    }


    private function getArrayColumn($array, $key)
    {
        $a = [];
        foreach ($array as $k => $v) {
            if (isset($v[$key])) {
                $a[] = $v[$key];
            }
        }

        return $a;
    }

    private function indexToAssoc($array, $key)
    {
        return array_combine(array_column($array, $key), array_values($array));
    }

    /*公会整体账户余额+收益余额(平台价值留存指标)*/
    public function sociatyEarningsKeep()
    {
        $sumEarnings = app('model_sc_sociaty')->sum('earnings');
        $sumMoney = app('model_sc_sociaty')->sum('money');

        return [
            'sumEarnings' => $sumEarnings,
            'sumMoney'    => $sumMoney,
        ];
    }

    /*公会 账户+收益收入（每日增量指标）*/
    public function sociatyEarningsInc($startTime, $endTime)
    {
        $sumMoney = app('model_sc_account_change')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->where(['symbol' => 1])->sum('change_money');

        return $sumMoney;
    }

    /*公会 账户+收益支出（每日减量指标）*/
    public function sociatyEarningsDec($startTime, $endTime)
    {
        $sumMoney = app('model_sc_account_change')->where('add_time', '>=', $startTime)->where('add_time', '<', $endTime)->where(['symbol' => 2])->sum('change_money');

        return $sumMoney;
    }


    public function getUserBackPackGiftNumber($userId)
    {
        return GiftBackpack::query()
            ->where('user_id', $userId)
            ->where('number', '>', 0)
            ->groupBy('gift_id')
            ->selectRaw('gift_id, sum(number) as number')
            ->get()
            ->toArray();
    }

    public function getUserBackPackPriceByUserId($userId)
    {
        $userBackGift = $this->getUserBackPackGiftNumber($userId);
        $userBackGift = array_column($userBackGift, 'number', 'gift_id');
        $giftIdArr = array_keys($userBackGift);
        if (empty($giftIdArr)) {
            return 0;
        }
        $giftInfo = Gift::query()->whereIn('id', $giftIdArr)->selectRaw('id, price')->get()->toArray();
        $giftTotalMoney = 0;
        foreach ($giftInfo as $v) {
            $giftId = $v['id'];
            $giftPrice = $v['price'];
            $giftTotalMoney += $giftPrice * $userBackGift[$giftId];
        }

        return $giftTotalMoney;
    }


    //用户总体砖石+  绑钻价值
    public function getAllDiamondsByUserId(int $userId = 0)
    {
        $balance = app('model_game_user')->sum('balance');
        $reward = app('model_game_user')->sum('reward');
        $rdata = [
            'blancne' => [
                'sum'  => $balance, //所有蓝钻数量
                'coin' => $balance * 100, //蓝砖价值气泡币数量
            ],
            'reward'  => [
                'sum' => $reward, //绑钻数量
            ],
        ];

        return $rdata;
    }

    public function getUserDiamondsByUserId($userId)
    {
        $isHave = app('model_game_user')->select(['balance', 'reward'])->where('id', $userId)->first();
        if (empty($isHave)) {
            return [
                'total_num' => 0,
                'bind_num'  => 0,
            ];
        }

        return [
            'total_num' => $isHave->balance,
            'bind_num'  => $isHave->reward,
        ];
    }

    public function getWaterNumberByUserId($userId)
    {
        $number = app('redis')->get('u:waterdrop:' . $userId);
        if (empty($number)) {
            $number = 0;
        }

        return $number;
    }


    public function getUserAccountByUserId($userId)
    {
        $userInfo = User::query()->where('user_id', $userId)->selectRaw('earnings, money')->first();
        DB::enableQueryLog();
        // 单表记录
        // 充值表
        $rechargeInfo = app('model_user_recharge')
            ->where('user_id', $userId)
            ->where('status', 2)
            ->whereBetween('add_time', [0, strtotime('2021-09-7')])
            ->groupBy('user_id')->selectRaw('count(1) as num,sum(gold) as money')
            ->first();
        // 送礼信息
        $giveGiftNumber = app('model_give_gift')
            ->where('user_id', $userId)
            ->groupBy('user_id')
            ->count('id');
        // 收礼信息
        $getGiftNumber = app('model_give_gift')
            ->where('gift_user', $userId)
            ->groupBy('gift_user')
            ->count('id');
        $account = AccountLog::query()
            ->where('user_id', $userId)
            ->whereBetween('change_time', [0, strtotime('2021-09-7')])
            ->selectRaw('count(1) as num, sum(user_money) as user_money, change_type')
            ->groupBy('change_type')
            ->get()
            ->toArray();
        $accountDetail = $this->handleAccount($account);
        $userAccountResult = $accountDetail['result'];
        //        $userAccountResult['money'] += $rechargeInfo->money;

        $backpackGiftTotalPrice = $this->getUserBackPackPriceByUserId($userId);
        $userWaterNumber = $this->getWaterNumberByUserId($userId);
        $userWaterPrice = $userWaterNumber == 0 ? 0 : $userWaterNumber * 200;
        $userDiamondsInfo = $this->getUserDiamondsByUserId($userId);
        $userDiamondsTotalNum = $userDiamondsInfo['total_num'];
        $userDiamondsBindNum = $userDiamondsInfo['bind_num'];
        $userDiamondsTotalPrice = $userDiamondsTotalNum * 100;
        $userTotalMoney = $userInfo['money'] + $backpackGiftTotalPrice + $userWaterPrice + $userDiamondsTotalPrice + $rechargeInfo->money; // todo 余额 + 背包礼物价值 + 水滴 * 200 + 充值金额
        //        $userTotalMoney = $userInfo['money'] + $backpackGiftTotalPrice + $userWaterPrice + $userDiamondsTotalPrice; // todo 余额 + 背包礼物价值 + 水滴 * 200 + 充值金额
        $result = [
            'user_info'    => [
                'total_money'         => $userTotalMoney,
                'money'               => $userInfo['money'],
                'earnings'            => $userInfo['earnings'],
                'backpack_gift_price' => $backpackGiftTotalPrice,
                'water_number'        => $userWaterNumber,
                'water_price'         => $userWaterPrice,
            ],
            'account_info' => $userAccountResult,
        ];


        $content = "【用户{$userId}】" . PHP_EOL;
        $content .= "账户总余额(余额+背包+水滴+钻石价值): {$userTotalMoney}" . PHP_EOL;
        $content .= "账户剩余余额: {$userInfo['money']}" . PHP_EOL;
        $content .= "账户剩余收益: {$userInfo['earnings']}" . PHP_EOL;
        $content .= "背包礼物价值: {$backpackGiftTotalPrice}" . PHP_EOL;
        $content .= "公会收益: 暂无此功能" . PHP_EOL; // todo
        $content .= "水滴数量: {$userWaterNumber}" . PHP_EOL;
        $content .= "水滴价值: {$userWaterPrice}" . PHP_EOL;
        $content .= "钻石价值: {$userDiamondsTotalPrice}" . PHP_EOL;
        $content .= "钻石数量: {$userDiamondsTotalNum}" . PHP_EOL;
        $content .= "绑定钻石数量: {$userDiamondsBindNum}" . PHP_EOL;
        $content .= "资金明细余额: {$userAccountResult['money']}" . PHP_EOL;
        $content .= "资金明细收益: {$userAccountResult['earnings']}" . PHP_EOL;
        $content .= "【资金明细余额】" . PHP_EOL;
        $content .= "money: 因充值(单数{$rechargeInfo->num}), 增加{$rechargeInfo->money}  价值:{$rechargeInfo->money}, 倍数: 1}" . PHP_EOL;  // todo 资金
        $content .= $accountDetail['tips']['money'];
        $content .= 'money: ' . $accountDetail['tips']['money_calculation'] . PHP_EOL;
        $content .= "【资金明细收益】" . PHP_EOL;
        $content .= $accountDetail['tips']['earnings'];
        $content .= 'earnings: ' . $accountDetail['tips']['earnings_calculation'] . PHP_EOL;
        $content .= "【单表查询】" . PHP_EOL;
        $content .= "充值: 金额{$rechargeInfo->money}, 数量: {$rechargeInfo->num}" . PHP_EOL; // todo 资金
        $content .= "收礼: 数量: {$getGiftNumber}" . PHP_EOL;
        $content .= "送礼: 数量: {$giveGiftNumber}" . PHP_EOL;
        $content .= '================================================================================' . PHP_EOL;
        $redis = app('redis');
        //        $addRes = $redis->sadd('account_user_log', $userId);
        $addRes = true;                                                                 // 调试用
        if ($addRes) {
            file_put_contents(__DIR__ . '/../../storage/logs/' . 'account_user.txt', $content, FILE_APPEND);
        }

        return [
            'result'  => $result,
            'content' => $content,
        ];
    }


    public function getUserAccountDetailByUserId($userId)
    {
        $account = AccountLog::query()
            ->where('user_id', $userId)
            ->selectRaw('id, user_money, change_desc, change_type, change_time')
            ->orderBy('id')
            ->get()
            ->toArray();
        $info = $this->handleAccountByMoney($account, $userId);
        $waterNumber = $info['count'];
        $money = $info['money'];
        app('redis')->incrby('test:money', $money);
        app('redis')->incrby('test:water:num', $waterNumber);

        return ['money' => $money, 'water_num' => $waterNumber];
    }

    public function handleAccountByMoney($account, $userId = 0)
    {
        $returnMoney = 0;
        $content = "【用户{$userId}】" . PHP_EOL;
        $count = $total = $mm = 0;
        foreach ($account as $v) {
            $accountId = $v['id'];
            $changType = $v['change_type'];
            $money = $v['user_money'];
            $desc = $v['change_desc'];
            $handleInfo = $this->getUserMoney();
            $handleName = $handleInfo[$changType]['name'];
            $handleMultiple = $handleInfo[$changType]['multiple'] ?? 1;
            $symbol = $handleInfo[$changType]['symbol'];
            $handleField = $handleInfo[$changType]['handle'] ?? 'money';
            $time = date("Y-m-d H:i:s", $v['change_time']);
            if ($money == 0 || $handleMultiple == 0 || $handleField != 'money') { // 只计算金币
                continue;
            }
            $opType = '增加';
            $score = $money * $handleMultiple;
            if ($symbol != 1) {
                $score = 0 - $score;
                $opType = '减少';
            }
            if ($returnMoney <= 0 && $score > 0) {
                $returnMoney = 0;
            }
            $returnMoney += $score;
            $content .= "【{$handleName}】ID:{$accountId}. {$opType}: {$score}, 剩余: {$returnMoney}" . "  【{$time}】" . PHP_EOL;
            if ($returnMoney < 0) {
                if ($changType == 133) {
                    $count++;
                } else {
                    $mm += abs($returnMoney);
                }
                //                $content .= '==================================================' . PHP_EOL;
                //                file_put_contents(__DIR__ . '/../../storage/logs/' . 'account_user_detail.txt', $content, FILE_APPEND);
                //                throw new BasicException(-1,"资金明细记录ID:{$accountId}, 扣除:{$score},原因:{$desc}, 导致余额出现负数: {$returnMoney}");

            }
            if ($changType == 133) {
                $total++;
            }
        }
        $content .= '==========================' . $count . '|' . $total . '|' . $mm . '===============================';
        //        file_put_contents(__DIR__ . '/../../storage/logs/' . 'account_user.txt', $content, FILE_APPEND);
        //        return $returnMoney;
        return [
            'count' => $count,
            'money' => $mm,
        ];
    }


    private function handleAccount($account)
    {
        $result = [
            'earnings' => 0,
            'money'    => 0,
        ];
        $handleInfo = $this->getUserMoney();
        $earningsCalculation = $earningsOpLog = $moneyCalculation = $moneyOpLog = '';
        foreach ($account as $v) {
            $changType = $v['change_type'];
            if (in_array($changType, [1])) { // 1. 充值不准跳过
                continue;
            }
            $money = $v['user_money'];
            $num = $v['num'];
            $handleField = $handleInfo[$changType]['handle'] ?? 'money';
            $handleMultiple = $handleInfo[$changType]['multiple'] ?? 1;
            $symbol = $handleInfo[$changType]['symbol'];
            if ($money == 0 || $handleMultiple == 0) {
                continue;
            }
            if ($symbol == 1) {
                $addScore = $money * $handleMultiple;
                $result[$handleField] += $addScore;
                if ($handleField == 'money') {
                    $moneyCalculation .= " + {$money} * {$handleMultiple}";
                    $moneyOpLog .= "{$handleField}: 因{$handleInfo[$changType]['name']}(单数{$num}), 增加{$addScore}  价值:{$money}, 倍数: {$handleMultiple}" . PHP_EOL;
                } else {
                    $earningsCalculation .= " + {$money} * {$handleMultiple}";
                    $earningsOpLog .= "{$handleField}: 因{$handleInfo[$changType]['name']}(单数{$num}), 增加{$addScore}  价值:{$money}, 倍数: {$handleMultiple}" . PHP_EOL;
                }
            } else {
                $decScore = $money * $handleMultiple;
                if ($changType == 8) {
                    $result['money'] += $decScore;
                    $moneyOpLog .= "money: 因{$handleInfo[$changType]['name']}(单数{$num}),  增加{$decScore}  价值:{$money}, 倍数: {$handleMultiple}" . PHP_EOL;
                    $moneyCalculation .= " + {$money} * {$handleMultiple}";
                }
                $result[$handleField] -= $decScore;
                if ($handleField == 'money') {
                    $moneyCalculation .= " - {$money} * {$handleMultiple}";
                    $moneyOpLog .= "{$handleField}: 因{$handleInfo[$changType]['name']}(单数{$num}), 减少{$decScore}  价值:{$money}, 倍数: {$handleMultiple}" . PHP_EOL;
                } else {
                    $earningsCalculation .= " - {$money} * {$handleMultiple}";
                    $earningsOpLog .= "{$handleField}: 因{$handleInfo[$changType]['name']}(单数{$num}), 减少{$decScore}  价值:{$money}, 倍数: {$handleMultiple}" . PHP_EOL;
                }
            }
        }

        return [
            'result' => $result,
            'tips'   => [
                'money'                => $moneyOpLog,
                'earnings'             => $earningsOpLog,
                'money_calculation'    => $moneyCalculation,
                'earnings_calculation' => $earningsCalculation,
            ],
        ];
    }

    public function getUserMoney()
    {
        return [
            1   => ['id' => 1, 'name' => '充值', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1], //  充值不准。外部通过充值表计算
            3   => ['id' => 3, 'name' => '小猫钓鱼', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            123 => ['id' => 123, 'name' => '小猫钓鱼', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            4   => ['id' => 4, 'name' => '赠送礼物', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            5   => ['id' => 5, 'name' => '购买爵位', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            6   => ['id' => 6, 'name' => '收到礼物', 'symbol' => 1, 'handle' => 'earnings', 'multiple' => 0.7],
            7   => ['id' => 7, 'name' => '购买爵位返利', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            8   => ['id' => 8, 'name' => '兑换金币', 'symbol' => 0, 'handle' => 'earnings', 'multiple' => 1],
            9   => ['id' => 9, 'name' => '赠送背包礼物', 'symbol' => 0, 'handle' => 'earnings', 'multiple' => 0],
            19  => ['id' => 19, 'name' => '购买个性商品', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            20  => ['id' => 20, 'name' => '爵位续费', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            21  => ['id' => 21, 'name' => '金币充值', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            22  => ['id' => 22, 'name' => '金币扣除', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            16  => ['id' => 16, 'name' => '收益增加', 'symbol' => 1, 'handle' => 'earnings', 'multiple' => 1],
            17  => ['id' => 17, 'name' => '收益减少', 'symbol' => 0, 'handle' => 'earnings', 'multiple' => 1],
            23  => ['id' => 23, 'name' => '提现中', 'symbol' => 0, 'handle' => 'earnings', 'multiple' => 0],
            2   => ['id' => 2, 'name' => '提现成功', 'symbol' => 0, 'handle' => 'earnings', 'multiple' => 1],
            24  => ['id' => 24, 'name' => '提现失败', 'symbol' => 1, 'handle' => 'earnings', 'multiple' => 1],
            25  => ['id' => 25, 'name' => '开通守护', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            26  => ['id' => 26, 'name' => '开通守护奖励', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            27  => ['id' => 27, 'name' => '余额增加', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            28  => ['id' => 28, 'name' => '余额减少', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            29  => ['id' => 29, 'name' => '收益增加', 'symbol' => 1, 'handle' => 'earnings', 'multiple' => 1],
            30  => ['id' => 30, 'name' => '收益减少', 'symbol' => 0, 'handle' => 'earnings', 'multiple' => 1],
            31  => ['id' => 31, 'name' => '余额冻结', 'symbol' => 0, 'handle' => 'money', 'multiple' => 0],
            32  => ['id' => 32, 'name' => '余额解冻', 'symbol' => 1, 'handle' => 'money', 'multiple' => 0],
            33  => ['id' => 33, 'name' => '粉丝通知', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            34  => ['id' => 34, 'name' => '礼包金币', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            35  => ['id' => 35, 'name' => '奖励发放', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            36  => ['id' => 36, 'name' => '订单付款', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            37  => ['id' => 37, 'name' => '订单拒接，账户回款', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            38  => ['id' => 38, 'name' => '订单取消，账户回款', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            39  => ['id' => 39, 'name' => '订单退款，账户回款', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            40  => ['id' => 40, 'name' => '订单结算，账户入账', 'symbol' => 1, 'handle' => 'earnings', 'multiple' => 0.8],
            50  => ['id' => 50, 'name' => '预购糖果', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            51  => ['id' => 51, 'name' => '预购糖果返还', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            52  => ['id' => 52, 'name' => '房间糖果扣金币', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            53  => ['id' => 53, 'name' => '房间糖果返还金币', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            54  => ['id' => 54, 'name' => '购买万圣节礼包', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            55  => ['id' => 55, 'name' => '打开道具赠送', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            56  => ['id' => 56, 'name' => '购买进阶战令', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            57  => ['id' => 57, 'name' => '购买战令等级', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            58  => ['id' => 58, 'name' => '竞拍成功', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            59  => ['id' => 59, 'name' => '被拍成功', 'symbol' => 1, 'handle' => 'earnings', 'multiple' => 0.7],
            60  => ['id' => 60, 'name' => '点唱消费', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            61  => ['id' => 61, 'name' => '点唱收益', 'symbol' => 1, 'handle' => 'earnings', 'multiple' => 0.7],
            62  => ['id' => 62, 'name' => '浪漫小镇助力', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            63  => ['id' => 63, 'name' => '七夕活动-转盘抽奖', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            100 => ['id' => 100, 'name' => '兑换蓝钻', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            133 => ['id' => 133, 'name' => '浇水', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            134 => ['id' => 134, 'name' => '抢头条', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            135 => ['id' => 135, 'name' => '签到活动（补签）', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            136 => ['id' => 136, 'name' => '年兽活动(攻击年兽支付金币)', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            140 => ['id' => 140, 'name' => '公会账户提取', 'symbol' => 1, 'handle' => 'earnings', 'multiple' => 1],
            141 => ['id' => 141, 'name' => '实现心愿', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            199 => ['id' => 199, 'name' => '购买背景墙', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            210 => ['id' => 210, 'name' => '使用互动表情', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            142 => ['id' => 142, 'name' => '发红包', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            143 => ['id' => 143, 'name' => '抢红包', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            144 => ['id' => 144, 'name' => '红包退还', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            160 => ['id' => 160, 'name' => '公会收益提取', 'symbol' => 1, 'handle' => 'money', 'multiple' => 1],
            161 => ['id' => 161, 'name' => '公会账户充值', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            220 => ['id' => 220, 'name' => '购买亲密道具', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            221 => ['id' => 221, 'name' => '购买亲密道具', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            102 => ['id' => 102, 'name' => '双11促销', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
            209 => ['id' => 209, 'name' => '我要上公屏', 'symbol' => 0, 'handle' => 'money', 'multiple' => 1],
        ];
    }

    //用户总体砖石+  绑钻价值
    public function allBalanceAndReward(int $userId = 0)
    {
        if ($userId == 0) { //统计所有游戏用户总和
            $balance = app('model_game_user')->sum('balance');
            $reward = app('model_game_user')->sum('reward');
            $rdata = [
                'blancne' => [
                    'sum'  => $balance, //所有蓝钻数量
                    'coin' => $balance * 100, //蓝砖价值气泡币数量
                ],
                'reward'  => [
                    'sum' => $reward, //绑钻数量
                ],
            ];

            return $rdata;
        } else { //单个用户
            $isHave = app('model_game_user')->select(['balance', 'reward'])->where('id', $userId)->first()->toArray();
            if (empty($isHave)) {
                return [];
            } else {
                $rdata = [
                    'blancne' => [
                        'balance' => $isHave['balance'],
                        'coin'    => $isHave['balance'] * 100,
                    ],
                    'reward'  => [
                        'sum' => $isHave['reward'], //绑钻数量
                    ],
                ];

                return $rdata;
            }
        }
    }

    /**
     * 某个时间段减量指标 霍克城堡总体返补 时间筛选为 左闭右开 区间   某个时间段的金币产出
     *
     * @param  int  $startTime  不传默认为今天00:00:00的时间戳
     * @param  int  $entTime  参数2不传默认为明天00:00:00时间戳
     * @return int
     */
    public function subGameData(int $startTime = 0, int $entTime = 0)
    {
        $startTime = $startTime == 0 ? date('Y-m-d', time()) . ' 00:00:00' : date('Y-m-d H:i:s', $startTime);
        $entTime = $entTime == 0 ? date('Y-m-d', strtotime('+1 day')) . ' 00:00:00' : date('Y-m-d H:i:s', $entTime);
        $where = [
            ['type', '=', 'gift'],
            ['created_at', '>=', $startTime],
            ['created_at', '<', $entTime],
        ];
        $res = app('model_game_order')->where($where)->selectRaw('sum(`price`*`count`) as allp')->first();
        if (empty($res)) {
            return 0;
        } else {
            return $res->allp;
        }
    }


    /**
     * 某个时间段内增量指标 霍克城堡总体返补 时间筛选为左闭右开区间  某段时间金币兑换蓝钻数
     *
     * @param  int  $startTime  不传默认为今天00:00:00的时间戳
     * @param  int  $entTime  不传默认为明天00:00:00时间戳
     * @return int
     */
    public function addGameData($startTime = 0, $entTime = 0)
    {
        $startTime = $startTime == 0 ? date('Y-m-d', time()) . ' 00:00:00' : date('Y-m-d H:i:s', $startTime);
        $entTime = $entTime == 0 ? date('Y-m-d', strtotime('+1 day')) . ' 00:00:00' : date('Y-m-d H:i:s', $entTime);

        $where = [
            ['source', '=', 'swap'],
            ['created_at', '>=', $startTime],
            ['created_at', '<', $entTime],
        ];

        $res = app('model_game_balance_log')->where($where)->selectRaw('sum(amount) as allamount')->first();
        if (empty($res)) {
            return 0;
        } else {
            return $res->allamount;
        }
    }


    /**
     * 某个时间段内 霍克游戏参与人数 左闭右开 区间
     *
     * @param  int  $startTime  不传默认为今天00:00:00的时间戳
     * @param  int  $entTime  不传默认为明天00:00:00时间戳
     * @return int
     */
    public function palyHuokeManNum($startTime = 0, $entTime = 0)
    {
        $startTime = $startTime == 0 ? date('Y-m-d', time()) . ' 00:00:00' : date('Y-m-d H:i:s', $startTime);
        $entTime = $entTime == 0 ? date('Y-m-d', strtotime('+1 day')) . ' 00:00:00' : date('Y-m-d H:i:s', $entTime);
        $where = [
            ['created_at', '>=', $startTime],
            ['created_at', '<', $entTime],
        ];
        $res = app('model_game_round_stat')->where($where)->selectRaw('sum(all_count) as all_count')->first();

        if (empty($res)) {
            return 0;
        } else {
            return $res->all_count;
        }
    }


    /**
     * 某个时间段内 霍克游戏下注数量 左闭右开 区间
     * @param  int  $startTime  不传默认为今天00:00:00的时间戳
     * @param  int  $entTime  不传默认为明天00:00:00时间戳
     * @return int
     */
    public function playHuokeTimeNum($startTime = 0, $entTime = 0)
    {
        $startTime = $startTime == 0 ? date('Y-m-d', time()) . ' 00:00:00' : date('Y-m-d H:i:s', $startTime);
        $entTime = $entTime == 0 ? date('Y-m-d', strtotime('+1 day')) . ' 00:00:00' : date('Y-m-d H:i:s', $entTime);
        $where = [
            ['created_at', '>=', $startTime],
            ['created_at', '<', $entTime],
        ];
        $res = app('model_game_bet')->where($where)->count();

        return $res;
    }

    /**
     * 霍克游戏时间段内的下注量 与中奖量
     *
     * @param  int  $startTime  不传默认为今天00:00:00的时间戳
     * @param  int  $entTime  不传默认为明天00:00:00时间戳
     */
    public function shakeHuoKe(int $startTime = 0, int $entTime = 0)
    {
        $startTime = $startTime == 0 ? date('Y-m-d', time()) . ' 00:00:00' : date('Y-m-d H:i:s', $startTime);
        $entTime = $entTime == 0 ? date('Y-m-d', strtotime('+1 day')) . ' 00:00:00' : date('Y-m-d H:i:s', $entTime);
        $where = [
            ['created_at', '>=', $startTime],
            ['created_at', '<', $entTime],
        ];
        $res = app('model_game_round')->where($where)->selectRaw('sum(input) as allinput,sum(output) as alloutput')->first();

        return $res;
    }

    /**
     * 游戏留存统计 根据时间添加搜索 左闭右开区间
     *
     * @param  int  $byTime  按照那种时间类型统计 1按小时 2按天
     * @param  int  $page
     * @param  int  $pageSize
     * @param  int  $startTime  0表示不筛选
     * @param  int  $endTime  0表示不筛选
     * @return array
     * @throws BasicException
     */
    public function hourKeepPrice(int $byTime, int $page = 1, int $pageSize = 20, int $startTime = 0, int $endTime = 0)
    {
        $result = [];
        $where = [];
        if ($startTime != 0 || $endTime != 0) {
            $where = [
                ['start_time', '>=', $startTime],
                ['start_time', '<', $endTime],
            ];
        }


        if ($byTime == 1) { //按小时

            if (empty($where)) {
                $ordertime = app('model_account_check_daily_stat')
                    ->orderBy('start_time', 'desc')
                    ->groupBy('start_time')
                    ->paginate($pageSize, ['*'], '', $page);
            } else {
                $ordertime = app('model_account_check_daily_stat')
                    ->where($where)
                    ->orderBy('start_time', 'desc')
                    ->groupBy('start_time')
                    ->paginate($pageSize, ['*'], '', $page);
            }


            $list = $ordertime->toArray();
            $byTime = array_column($list['data'], 'start_time');
            $data = app('model_account_check_daily_stat')->whereIn('start_time', $byTime)->whereIn('change_type', [9, 22, 23, 32, 19, 28, 21, 30, 25, 27, 34, 36, 40, 41])->orderBy('start_time', 'desc')->get()->toArray();

            $timeArr = array_column($data, 'start_time');
            $timeArr = array_unique($timeArr);

            $res = [];
            foreach ($timeArr as $key => $tv) {
                $tempArr = [];
                foreach ($data as $dv) {
                    if ($dv['start_time'] == $tv) {
                        $tempArr['start_time'] = $tv;
                        switch ($dv['change_type']) {
                            case AccountCheckEnum::TREE_ADD:
                                $tempArr['tree']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_MONEY_DECR:
                                $tempArr['tree']['sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::HU_KE_GAME_ADD:
                                $tempArr['hu']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::HU_KE_GAME_OUT:
                                $tempArr['hu']['sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::GIFT_BOX_MONEY_BUY:
                                $tempArr['gift']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::GIFT_BOX_MONEY_OUT:
                                $tempArr['gift']['sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::CANDY_MONEY_BUY:
                                $tempArr['candy']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::CANDY_MONEY_OUT:
                                $tempArr['candy']['sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_ADD_COMMON:
                                $tempArr['tree_common']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_MONEY_DECR_COMMON:
                                $tempArr['tree_common']['sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_ADD_SELF:
                                $tempArr['tree_self']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_MONEY_DECR_SELF:
                                $tempArr['tree_self']['sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::STAR_ADD_COMMON:
                                $tempArr['star']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::STAR_MONEY_DECR_COMMON:
                                $tempArr['star']['sum'] = intval(abs($dv['money']));
                                break;
                        }
                    }
                }
                foreach ($tempArr as $key => $value) {
                    if (is_array($value)) {
                        $add = $value['add'] ?? 0;
                        $sum = $value['sum'] ?? 0;
                        $tempGain = $add - $sum;
                        $tempArr[$key]['gain'] = $tempGain < 0 ? $tempGain : '+' . $tempGain;
                    }
                }
                array_push($res, $tempArr);
            }


            $result = [
                'total'        => $list['total'] ?? 0,
                'current_page' => $list['current_page'] ?? 1,
                'last_page'    => $list['last_page'] ?? 1,
                'list'         => $res,
            ];
        } else {
            if (empty($where)) {
                $ordertime = app('model_account_check_daily_stat_real')
                    ->orderBy('start_time', 'desc')
                    ->groupBy('start_time')
                    ->paginate($pageSize, ['*'], '', $page);
            } else {
                $ordertime = app('model_account_check_daily_stat_real')
                    ->where($where)
                    ->orderBy('start_time', 'desc')
                    ->groupBy('start_time')
                    ->paginate($pageSize, ['*'], '', $page);
            }


            $list = $ordertime->toArray();
            $byTime = array_column($list['data'], 'start_time');
            $data = app('model_account_check_daily_stat_real')->whereIn('start_time', $byTime)->whereIn('change_type', [9, 22, 23, 32, 19, 28, 21, 30, 25, 27, 34, 36, 40, 41])->orderBy('start_time', 'desc')->get()->toArray();

            $timeArr = array_column($data, 'start_time');
            $timeArr = array_unique($timeArr);
            $res = [];
            foreach ($timeArr as $key => $tv) {
                $tempArr = [];
                foreach ($data as $dv) {
                    $tempArr['start_time'] = $tv;
                    if ($dv['start_time'] == $tv) {
                        switch ($dv['change_type']) {
                            case AccountCheckEnum::TREE_ADD:
                                $tempArr['tree']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_MONEY_DECR:
                                $tempArr['tree']['sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::HU_KE_GAME_ADD:
                                $tempArr['hu']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::HU_KE_GAME_OUT:
                                $tempArr['hu']['sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::GIFT_BOX_MONEY_BUY:
                                $tempArr['gift']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::GIFT_BOX_MONEY_OUT:
                                $tempArr['gift']['sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::CANDY_MONEY_BUY:
                                $tempArr['candy']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::CANDY_MONEY_OUT:
                                $tempArr['candy']['sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_ADD_COMMON:
                                $tempArr['tree_common']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_MONEY_DECR_COMMON:
                                $tempArr['tree_common']['sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_ADD_SELF:
                                $tempArr['tree_self']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_MONEY_DECR_SELF:
                                $tempArr['tree_self']['sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::STAR_ADD_COMMON:
                                $tempArr['star']['add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::STAR_MONEY_DECR_COMMON:
                                $tempArr['star']['sum'] = intval(abs($dv['money']));
                                break;
                        }
                    }
                }
                foreach ($tempArr as $key => $value) {
                    if (is_array($value)) {
                        $add = $value['add'] ?? 0;
                        $sum = $value['sum'] ?? 0;
                        $tempGain = $add - $sum;

                        $tempArr[$key]['gain'] = $tempGain < 0 ? $tempGain : '+' . $tempGain;
                    }
                }
                array_push($res, $tempArr);
            }
            $result = [
                'total'        => $list['total'] ?? 0,
                'current_page' => $list['current_page'] ?? 1,
                'last_page'    => $list['last_page'] ?? 1,
                'list'         => $res,
            ];
        }

        return $result;
    }


    /**
     * 商城购买统计
     *
     * @param  int  $page
     * @param  int  $pageSize
     */
    public function forDayMallCate(int $page, int $pageSize, int $startTime = 0, int $endTime = 0)
    {
        $where = [];
        if ($startTime != 0 || $endTime != 0) {
            $where = [
                ['start_time', '>=', $startTime],
                ['start_time', '<', $endTime],
            ];
        }
        if (empty($where)) {
            $ordertime = app('model_mall_stat')
                ->whereIn('cate_id', [-1, 1, 2, 4, 7, 8, 23, 24, 25, 26, 27, 33])
                ->orderBy('start_time')
                ->groupBy('start_time')
                ->paginate($pageSize, ['*'], '', $page);
        } else {
            $ordertime = app('model_mall_stat')
                ->where($where)
                ->whereIn('cate_id', [-1, 1, 2, 4, 7, 8, 23, 24, 25, 26, 27, 33])
                ->orderBy('start_time')
                ->groupBy('start_time')
                ->paginate($pageSize, ['*'], '', $page);
        }

        if (empty($ordertime)) {
            return [];
        }
        $list = $ordertime->toArray();
        if (empty($list['data'])) {
            throw  new BasicException(10001, '没有数据了');
        }
        $byTime = array_column($list['data'], 'start_time');

        $data = app('model_mall_stat')->whereIn('cate_id', [-1, 1, 2, 4, 7, 8, 23, 24, 25, 26, 27, 33])->whereIn('start_time', $byTime)->get()->toArray();
        $timeArr = array_column($data, 'start_time');
        $timeArr = array_unique($timeArr);

        $res = [];
        foreach ($timeArr as $key => $tv) {
            $tempArr = [];
            foreach ($data as $dv) {
                if ($dv['start_time'] == $tv) {
                    $tempArr['start_time'] = $tv;
                    $tempArr[$dv['cate_id']] = ['cate_id' => $dv['cate_id'], 'money' => $dv['money']];
                }
            }
            array_push($res, $tempArr);
        }
        $result = [
            'total'        => $list['total'] ?? 0,
            'current_page' => $list['current_page'] ?? 1,
            'last_page'    => $list['last_page'] ?? 1,
            'list'         => $res,
        ];

        return $result;
    }

    //商城留存统计  不翻页
    public function forDayMallCateAllDate(int $startTime = 0, int $endTime = 0)
    {
        $where = [];
        if ($startTime != 0 || $endTime != 0) {
            $where = [
                ['start_time', '>=', $startTime],
                ['start_time', '<', $endTime],
            ];
        }
        if (empty($where)) {
            $ordertime = app('model_mall_stat')
                ->whereIn('cate_id', [-1, 1, 2, 4, 7, 8, 23, 24, 25, 26, 27, 33])
                ->orderBy('start_time')
                ->groupBy('start_time')
                ->get();
        } else {
            $ordertime = app('model_mall_stat')
                ->where($where)
                ->whereIn('cate_id', [-1, 1, 2, 4, 7, 8, 23, 24, 25, 26, 27, 33])
                ->orderBy('start_time')
                ->groupBy('start_time')
                ->get();
        }

        if (empty($ordertime)) {
            return [];
        }
        $list = $ordertime->toArray();

        $byTime = array_column($list, 'start_time');
        $data = app('model_mall_stat')->whereIn('cate_id', [-1, 1, 2, 4, 7, 8, 23, 24, 25, 26, 27, 33])->whereIn('start_time', $byTime)->get()->toArray();
        $timeArr = array_column($data, 'start_time');
        $timeArr = array_unique($timeArr);
        $res = [];

        $cateTitleData = app('model_mall_categories')->whereIn('id', [1, 2, 4, 7, 8, 23, 24, 25, 26, 27, 33])->pluck('title', 'id')->toArray();
        $cateTitleData['-1'] = '全部';

        $cateTitle = ['start_time' => '开始时间'] + $cateTitleData;

        foreach ($timeArr as $key => $tv) {
            $tempArr = [];
            foreach ($data as $dv) {
                if ($dv['start_time'] == $tv) {
                    $tempArr['start_time'] = date('Y-m-d H:i:s', $tv);
                    $tempArr[$dv['cate_id']] = $dv['money'];
                }
            }


            $tempArr['start_time'] = $tempArr['start_time'] ?? 0;
            $tempArr['-1'] = $tempArr['-1'] ?? 0;
            $tempArr['1'] = $tempArr['1'] ?? 0;
            $tempArr['2'] = $tempArr['2'] ?? 0;
            $tempArr['4'] = $tempArr['4'] ?? 0;
            $tempArr['7'] = $tempArr['7'] ?? 0;
            $tempArr['8'] = $tempArr['8'] ?? 0;
            $tempArr['23'] = $tempArr['23'] ?? 0;
            $tempArr['24'] = $tempArr['24'] ?? 0;
            $tempArr['25'] = $tempArr['25'] ?? 0;
            $tempArr['26'] = $tempArr['26'] ?? 0;
            $tempArr['27'] = $tempArr['27'] ?? 0;
            $tempArr['33'] = $tempArr['33'] ?? 0;
            array_push($res, $tempArr);
        }

        return ['stat' => $res, 'cateTitle' => $cateTitle];
    }

    //游戏留存统计 所有数据
    public function hourKeepPriceAllData($byTime = 1, $startTime = 0, $endTime = 0)
    {
        $where = [];
        if ($startTime != 0 || $endTime != 0) {
            $where = [
                ['start_time', '>=', $startTime],
                ['start_time', '<', $endTime],
            ];
        }


        if ($byTime == 1) { //按小时

            if (empty($where)) {
                $ordertime = app('model_account_check_daily_stat')
                    ->orderBy('start_time')
                    ->groupBy('start_time')
                    ->get();
            } else {
                $ordertime = app('model_account_check_daily_stat')
                    ->where($where)
                    ->orderBy('start_time')
                    ->groupBy('start_time')
                    ->get();
            }


            $list = $ordertime->toArray();

            $byTime = array_column($list, 'start_time');

            $data = app('model_account_check_daily_stat')->whereIn('start_time', $byTime)->whereIn('change_type', [9, 22, 23, 32, 19, 28, 21, 30, 25, 27, 34, 36, 40, 41])->get()->toArray();

            $timeArr = array_column($data, 'start_time');
            $timeArr = array_unique($timeArr);

            $res = [];
            foreach ($timeArr as $key => $tv) {
                $tempArr = [];
                foreach ($data as $dv) {
                    if ($dv['start_time'] == $tv) {
                        $tempArr['start_time'] = $tv;
                        switch ($dv['change_type']) {
                            case AccountCheckEnum::TREE_ADD:
                                $tempArr['tree.add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_MONEY_DECR:
                                $tempArr['tree.sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::HU_KE_GAME_ADD:
                                $tempArr['hu.add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::HU_KE_GAME_OUT:
                                $tempArr['hu.sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::GIFT_BOX_MONEY_BUY:
                                $tempArr['gift.add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::GIFT_BOX_MONEY_OUT:
                                $tempArr['gift.sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::CANDY_MONEY_BUY:
                                $tempArr['candy.add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::CANDY_MONEY_OUT:
                                $tempArr['candy.sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_ADD_COMMON:
                                $tempArr['tree_common.add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_MONEY_DECR_COMMON:
                                $tempArr['tree_common.sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::STAR_ADD_COMMON:
                                $tempArr['star.add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::STAR_MONEY_DECR_COMMON:
                                $tempArr['star.sum'] = intval(abs($dv['money']));
                                break;
                        }
                    }
                }
                $tempArr['candy.add'] = $tempArr['candy.add'] ?? 0;
                $tempArr['candy.sum'] = $tempArr['candy.sum'] ?? 0;

                $tempArr['gift.add'] = $tempArr['gift.add'] ?? 0;
                $tempArr['gift.sum'] = $tempArr['gift.sum'] ?? 0;

                $tempArr['hu.add'] = $tempArr['hu.add'] ?? 0;
                $tempArr['hu.sum'] = $tempArr['hu.sum'] ?? 0;

                $tempArr['tree.add'] = $tempArr['tree.add'] ?? 0;
                $tempArr['tree.sum'] = $tempArr['tree.sum'] ?? 0;

                $tempArr['tree_common.add'] = $tempArr['tree_common.add'] ?? 0;
                $tempArr['tree_common.sum'] = $tempArr['tree_common.sum'] ?? 0;

                $tempArr['star.add'] = $tempArr['star.add'] ?? 0;
                $tempArr['star.sum'] = $tempArr['star.sum'] ?? 0;

                $tempArr['candy.gain'] = $tempArr['candy.add'] - $tempArr['candy.sum'];
                $tempArr['gift.gain'] = $tempArr['gift.add'] - $tempArr['gift.sum'];
                $tempArr['hu.gain'] = $tempArr['hu.add'] - $tempArr['hu.sum'];
                $tempArr['tree.gain'] = $tempArr['tree.add'] - $tempArr['tree.sum'];
                $tempArr['tree_common.gain'] = $tempArr['tree_common.add'] - $tempArr['tree_common.sum'];
                $tempArr['star.gain'] = $tempArr['star.add'] - $tempArr['star.sum'];
                $tempArr['start_time'] = date('Y-m-d H:i:s', $tempArr['start_time']);

                array_push($res, $tempArr);
            }
            $result = $res;
        } else {
            if (empty($where)) {
                $ordertime = app('model_account_check_daily_stat_real')
                    ->orderBy('start_time')
                    ->groupBy('start_time')
                    ->get();
            } else {
                $ordertime = app('model_account_check_daily_stat_real')
                    ->where($where)
                    ->orderBy('start_time')
                    ->groupBy('start_time')
                    ->get();
            }


            $list = $ordertime->toArray();
            $byTime = array_column($list, 'start_time');
            $data = app('model_account_check_daily_stat_real')->whereIn('start_time', $byTime)->whereIn('change_type', [9, 22, 23, 32, 19, 28, 21, 30, 25, 27, 34, 36, 40, 41])->get()->toArray();

            $timeArr = array_column($data, 'start_time');
            $timeArr = array_unique($timeArr);
            $res = [];
            foreach ($timeArr as $key => $tv) {
                $tempArr = [];
                foreach ($data as $dv) {
                    $tempArr['start_time'] = $tv;
                    if ($dv['start_time'] == $tv) {
                        switch ($dv['change_type']) {
                            case AccountCheckEnum::TREE_ADD:
                                $tempArr['tree.add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_MONEY_DECR:
                                $tempArr['tree.sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::HU_KE_GAME_ADD:
                                $tempArr['hu.add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::HU_KE_GAME_OUT:
                                $tempArr['hu.sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::GIFT_BOX_MONEY_BUY:
                                $tempArr['gift.add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::GIFT_BOX_MONEY_OUT:
                                $tempArr['gift.sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::CANDY_MONEY_BUY:
                                $tempArr['candy.add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::CANDY_MONEY_OUT:
                                $tempArr['candy.sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_ADD_COMMON:
                                $tempArr['tree_common.add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::TREE_MONEY_DECR_COMMON:
                                $tempArr['tree_common.sum'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::STAR_ADD_COMMON:
                                $tempArr['star.add'] = intval(abs($dv['money']));
                                break;
                            case AccountCheckEnum::STAR_MONEY_DECR_COMMON:
                                $tempArr['star.sum'] = intval(abs($dv['money']));
                                break;
                        }
                    }
                }
                $tempArr['candy.add'] = $tempArr['candy.add'] ?? 0;
                $tempArr['candy.sum'] = $tempArr['candy.sum'] ?? 0;

                $tempArr['gift.add'] = $tempArr['gift.add'] ?? 0;
                $tempArr['gift.sum'] = $tempArr['gift.sum'] ?? 0;

                $tempArr['hu.add'] = $tempArr['hu.add'] ?? 0;
                $tempArr['hu.sum'] = $tempArr['hu.sum'] ?? 0;

                $tempArr['tree.add'] = $tempArr['tree.add'] ?? 0;
                $tempArr['tree.sum'] = $tempArr['tree.sum'] ?? 0;

                $tempArr['tree_common.add'] = $tempArr['tree_common.add'] ?? 0;
                $tempArr['tree_common.sum'] = $tempArr['tree_common.sum'] ?? 0;

                $tempArr['star.add'] = $tempArr['star.add'] ?? 0;
                $tempArr['star.sum'] = $tempArr['star.sum'] ?? 0;

                $tempArr['candy.gain'] = $tempArr['candy.add'] - $tempArr['candy.sum'];
                $tempArr['gift.gain'] = $tempArr['gift.add'] - $tempArr['gift.sum'];
                $tempArr['hu.gain'] = $tempArr['hu.add'] - $tempArr['hu.sum'];
                $tempArr['tree.gain'] = $tempArr['tree.add'] - $tempArr['tree.sum'];
                $tempArr['tree_common.gain'] = $tempArr['tree_common.add'] - $tempArr['tree_common.sum'];
                $tempArr['star.gain'] = $tempArr['star.add'] - $tempArr['star.sum'];
                $tempArr['start_time'] = date('Y-m-d H:i:s', $tempArr['start_time']);
                array_push($res, $tempArr);
            }
            $result = $res;
        }

        return $result;
    }


    //同步历史平台留存
    public function syncPlatFormKeep()
    {
        $remains = app('model_account_remind')->where('created_at','like',"%00:00:%")->orderBy('id','asc')->get();
        foreach ($remains as $item) {
            $day = explode(' ', $item->created_at);
            $start_time = strtotime($day[0]);
            $stime = $start_time - 86400;
            $exist = app('model_account_remain_stat')->where('start_time', $stime)
                ->where('ranges', 1)
                ->first();
            if (is_null($exist)) {
                $data = [
                    'origin_data' => $item->origin_data,
                    'out_text' => $item->out_text,
                    'start_time' => $stime,
                    'end_time' => $start_time-1,
                    'ranges' => 1,
                ];
                app('model_account_remain_stat')->insert($data);
            }

            //当前日期是周一,时间周期是上周
            if ((int)date('N',$start_time)===1){
                $week_start_time = strtotime(date('Y-m-d',$start_time)) - 86400*7;
                $week_exist = app('model_account_remain_stat')->where('start_time', $week_start_time)
                    ->where('ranges', 2)
                    ->first();
                if (is_null($week_exist)) {
                    $data = [
                        'origin_data' => $item->origin_data,
                        'out_text' => $item->out_text,
                        'start_time' => $week_start_time,
                        'end_time' => $start_time-1,
                        'ranges' => 2,
                    ];
                    app('model_account_remain_stat')->insert($data);
                }
            }
            //当前日期是1号,时间周期是上月
            if ((int)date('j',$start_time)===1){
                $month_start_time = mktime(0,0,0,date("n",$start_time)-1,1,date("Y",$start_time));
                $month_exist = app('model_account_remain_stat')->where('start_time', $month_start_time)
                    ->where('ranges', 3)
                    ->first();
                if (is_null($month_exist)) {
                    $data = [
                        'origin_data' => $item->origin_data,
                        'out_text' => $item->out_text,
                        'start_time' => $month_start_time,
                        'end_time' => $start_time-1,
                        'ranges' => 3,
                    ];
                    app('model_account_remain_stat')->insert($data);
                }
            }
        }
    }

    public function syncGameKeep($type)
    {
        if ($type==1){
            $this->syncDayGameKeep();
        }
        if ($type==2){
            $this->syncWeekGameKeep();
        }
        if ($type==3){
            $this->syncMonthGameKeep();
        }

    }
    //同步历史游戏留存
    public function syncDayGameKeep()
    {
        $games = app('model_account_check_daily_stat_real')->get();
        foreach ($games as $game){
            $insert = [];
            if ($game['start_time']==0){
                continue;
            }
            if($game['start_time'] == strtotime(date('Y-m-d'))){
                break;
            }
            switch ($game['change_type']) {
                case AccountCheckEnum::TREE_ADD:
                    $insert['fish_leap_add'] = (int)abs($game['money']);
                    break;
                case AccountCheckEnum::TREE_MONEY_DECR:
                    $insert['fish_leap_sum'] = (int)abs($game['money']);
                    break;
                case AccountCheckEnum::GIFT_BOX_MONEY_BUY:
                    $insert['treasure_box_add'] =  (int)abs($game['money']);
                    break;
                case AccountCheckEnum::GIFT_BOX_MONEY_OUT:
                    $insert['treasure_box_sum'] =  (int)abs($game['money']);
                    break;
                case AccountCheckEnum::TREE_ADD_COMMON:
                    $insert['fish_leap_common_add'] = (int)abs($game['money']);
                    break;
                case AccountCheckEnum::TREE_MONEY_DECR_COMMON:
                    $insert['fish_leap_common_sum'] = (int)abs($game['money']);
                    break;
                case AccountCheckEnum::STAR_ADD_COMMON:
                    $insert['lucky_spin_add'] = (int)abs($game['money']);
                    break;
                case AccountCheckEnum::STAR_MONEY_DECR_COMMON:
                    $insert['lucky_spin_sum'] = (int)abs($game['money']);
                    break;
            }
            $insert['ranges'] = 1;
            $insert['start_time'] = $game['start_time'];
            $insert['end_time'] = $game['end_time']-1;
            $insert['created_at'] = time();
            $dayexist = app('model_account_game_data')->where('start_time',$game['start_time'])
//                ->where('end_time',$game['end_time'])
                ->where('ranges',1)
                ->first();
            if ($dayexist){
                app('model_account_game_data')->where('id',$dayexist->id)->update($insert);
            }else{
                app('model_account_game_data')->insert($insert);
            }

        }

        //处理收益计算
        $stats = app('model_account_game_data')->get();
        foreach ($stats as $st){
            $update = [];
            $treasure_box_gain =  $st->treasure_box_add - $st->treasure_box_sum;
            $update['treasure_box_gain'] = $treasure_box_gain > 0 ? '+'.$treasure_box_gain : $treasure_box_gain;
            $fish_leap_gain = $st->fish_leap_add - $st->fish_leap_sum;
            $update['fish_leap_gain'] = $fish_leap_gain > 0 ? '+'.$fish_leap_gain : $fish_leap_gain;
            $fish_leap_common_gain = $st->fish_leap_common_add - $st->fish_leap_common_sum;
            $update['fish_leap_common_gain'] = $fish_leap_common_gain > 0 ? '+'.$fish_leap_common_gain : $fish_leap_common_gain;
            $lucky_spin_gain = $st->lucky_spin_add - $st->lucky_spin_sum;
            $update['lucky_spin_gain'] = $lucky_spin_gain > 0 ? '+'.$lucky_spin_gain : $lucky_spin_gain;

            app('model_account_game_data')->where('id',$st->id)->update($update);
        }
    }

    public function syncWeekGameKeep()
    {
        $first = app('model_account_game_data')->where('ranges',1)->orderBy('start_time','asc')->first();
        $start = $first->start_time-(date('N',$first->start_time)-1)*86400;
        for ($i=0;$i<=1000;$i++){
            $end = $start+86400*7-1;
            if (date('W',$start) == date('W')){
                break;
            }
            $exist = app('model_account_game_data')->where('start_time',$start)
                ->where('ranges',2)
                ->first();
            if ($exist){
                $start+=86400*7;
                continue;
            }

            $stats = app('model_account_game_data')
                ->where('start_time','>=',$start)
                ->where('start_time','<=',$end)
                ->where('ranges',1)
                ->get();
                $treasure_box_add = 0;
                $treasure_box_sum=0;
                $treasure_box_gain=0;
                $fish_leap_add=0;
                $fish_leap_sum=0;
                $fish_leap_gain=0;
                $fish_leap_common_add=0;
                $fish_leap_common_sum=0;
                $fish_leap_common_gain=0;
                $lucky_spin_add = 0;
                $lucky_spin_sum = 0;
                $lucky_spin_gain = 0;

            foreach ($stats as $t){
                $treasure_box_add += $t['treasure_box_add'];
                $treasure_box_sum += $t['treasure_box_sum'];
                $treasure_box_gain += $t['treasure_box_gain'];
                $fish_leap_add += $t['fish_leap_add'];
                $fish_leap_sum += $t['fish_leap_sum'];
                $fish_leap_gain += $t['fish_leap_gain'];
                $fish_leap_common_add += $t['fish_leap_common_add'];
                $fish_leap_common_sum += $t['fish_leap_common_sum'];
                $fish_leap_common_gain += $t['fish_leap_common_gain'];
                $lucky_spin_add += $t['lucky_spin_add'];
                $lucky_spin_sum += $t['lucky_spin_sum'];
                $lucky_spin_gain += $t['lucky_spin_gain'];
            }
//            echo date('Y-m-d H:i:s',$start).PHP_EOL;
//            echo date('Y-m-d H:i:s',$end).PHP_EOL;
            $saved = app('model_account_game_data')->insert([
                'treasure_box_add'   => $treasure_box_add,
                'treasure_box_sum'   => $treasure_box_sum,
                'treasure_box_gain'  => $treasure_box_gain,
                'fish_leap_add'      => $fish_leap_add,
                'fish_leap_sum'      => $fish_leap_sum,
                'fish_leap_gain'     => $fish_leap_gain,
                'fish_leap_common_add'=> $fish_leap_common_add,
                'fish_leap_common_sum'=> $fish_leap_common_sum,
                'fish_leap_common_gain'=> $fish_leap_common_gain,
                'lucky_spin_add'     => $lucky_spin_add,
                'lucky_spin_sum'     => $lucky_spin_sum,
                'lucky_spin_gain'    => $lucky_spin_gain,
                'lucky_spin_common_add'=> 0,
                'lucky_spin_common_sum'=> 0,
                'lucky_spin_common_gain'=> 0,
                'start_time'        =>  $start,
                'end_time'          =>  $end,
                'ranges'            =>  2,
                'created_at'        =>  $start,
            ]);
            $start+=86400*7;
        }
    }



    public function syncMonthGameKeep()
    {
        $first = app('model_account_game_data')->where('ranges',1)->orderBy('start_time','asc')->first();
        $month = date("n",$first->start_time);
        for ($i=0;$i<=1000;$i++){
            $start = mktime(0,0,0,$month,1,date("Y",$first->start_time));
            $endMonth = $month+1;
            $end = mktime(0,0,0,$endMonth,1,date("Y",$first->start_time))-1;
            if (date('n',$start) == date('n')){
                break;
            }
            $exist = app('model_account_game_data')->where('start_time',$start)
                ->where('ranges',3)
                ->first();
            if ($exist){
                $month++;
                continue;
            }

            $stats = app('model_account_game_data')
                ->where('start_time','>=',$start)
                ->where('start_time','<=',$end)
                ->where('ranges',1)
                ->get();
            $treasure_box_add = 0;
            $treasure_box_sum=0;
            $treasure_box_gain=0;
            $fish_leap_add=0;
            $fish_leap_sum=0;
            $fish_leap_gain=0;
            $fish_leap_common_add=0;
            $fish_leap_common_sum=0;
            $fish_leap_common_gain=0;
            $lucky_spin_add = 0;
            $lucky_spin_sum = 0;
            $lucky_spin_gain = 0;

            foreach ($stats as $t){
                $treasure_box_add += $t['treasure_box_add'];
                $treasure_box_sum += $t['treasure_box_sum'];
                $treasure_box_gain += $t['treasure_box_gain'];
                $fish_leap_add += $t['fish_leap_add'];
                $fish_leap_sum += $t['fish_leap_sum'];
                $fish_leap_gain += $t['fish_leap_gain'];
                $fish_leap_common_add += $t['fish_leap_common_add'];
                $fish_leap_common_sum += $t['fish_leap_common_sum'];
                $fish_leap_common_gain += $t['fish_leap_common_gain'];
                $lucky_spin_add += $t['lucky_spin_add'];
                $lucky_spin_sum += $t['lucky_spin_sum'];
                $lucky_spin_gain += $t['lucky_spin_gain'];
            }
//            echo date('Y-m-d H:i:s',$start).PHP_EOL;
//            echo date('Y-m-d H:i:s',$end).PHP_EOL;
            $saved = app('model_account_game_data')->insert([
                'treasure_box_add'   => $treasure_box_add,
                'treasure_box_sum'   => $treasure_box_sum,
                'treasure_box_gain'  => $treasure_box_gain,
                'fish_leap_add'      => $fish_leap_add,
                'fish_leap_sum'      => $fish_leap_sum,
                'fish_leap_gain'     => $fish_leap_gain,
                'fish_leap_common_add'=> $fish_leap_common_add,
                'fish_leap_common_sum'=> $fish_leap_common_sum,
                'fish_leap_common_gain'=> $fish_leap_common_gain,
                'lucky_spin_add'     => $lucky_spin_add,
                'lucky_spin_sum'     => $lucky_spin_sum,
                'lucky_spin_gain'    => $lucky_spin_gain,
                'lucky_spin_common_add'=> 0,
                'lucky_spin_common_sum'=> 0,
                'lucky_spin_common_gain'=> 0,
                'start_time'        =>  $start,
                'end_time'          =>  $end,
                'ranges'            =>  3,
                'created_at'        =>  $start,
            ]);
           $month++;
        }
    }
}
